<template>
	<!-- 调试信息已移除 -->
	<view class="login-modal" v-if="visible" @tap.stop="handleMaskClick">
		<!-- 自定义Toast组件 (H5专用) -->
		<!-- #ifdef H5 -->
		<view class="custom-toast" v-if="toastInfo.show" :class="toastInfo.type">
			<text class="toast-text">{{ toastInfo.message }}</text>
		</view>
		<!-- #endif -->
		
		<view class="modal-content" @tap.stop="">
			<view class="modal-header">
				<text class="modal-title">用户登录</text>
				<text class="close-btn" @tap="closeModal" v-if="!required">×</text>
			</view>
			
			<view class="modal-body">
				<view class="form-item">
					<text class="form-label">用户名</text>
					<input 
						class="form-input" 
						v-model="loginForm.account" 
						placeholder="请输入用户名"
						:focus="focusUsername"
						@blur="focusUsername = false"
					/>
				</view>
				
				<view class="form-item">
					<text class="form-label">密码</text>
					<input 
						class="form-input" 
						v-model="loginForm.password" 
						placeholder="请输入密码"
						password
						:focus="focusPassword"
						@blur="focusPassword = false"
					/>
				</view>
				
				<view class="form-item checkbox-item">
					<label class="checkbox-label">
						<checkbox 
							:checked="loginForm.rememberMe" 
							@change="onRememberChange"
							color="#2B5BA1"
						/>
						<text class="checkbox-text">记住密码</text>
					</label>
				</view>
			</view>
			
			<view class="modal-footer">
				<button 
					class="login-btn" 
					@tap="handleLogin"
					:disabled="!canLogin"
					:loading="loading"
				>
					{{ loading ? '登录中...' : '登录' }}
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { loginApi, saveLoginData, saveCredentials, getSavedCredentials, clearSavedCredentials } from '@/common/auth'

// Props
const props = defineProps({
	visible: {
		type: Boolean,
		default: false
	},
	required: {
		type: Boolean,
		default: true // 是否必须登录（不能关闭）
	}
})

// Emits
const emit = defineEmits(['update:visible', 'login-success', 'close'])

// 响应式数据
const loginForm = ref({
	account: '',
	password: '',
	rememberMe: false
})

const loading = ref(false)
const focusUsername = ref(false)
const focusPassword = ref(false)

// Toast相关数据
const toastInfo = ref({
	show: false,
	message: '',
	type: 'success' // success | error
})

// 计算属性
const canLogin = computed(() => {
	return loginForm.value.account.trim() && loginForm.value.password.trim()
})

// 方法
const handleMaskClick = () => {
	if (!props.required) {
		closeModal()
	}
}

const closeModal = () => {
	if (!props.required) {
		emit('update:visible', false)
		emit('close')
	}
}

const onRememberChange = (e) => {
	loginForm.value.rememberMe = e.detail.value.length > 0
}

// 自定义Toast方法，兼容H5环境
const showToast = (options) => {
	// #ifdef H5
	// H5环境使用自定义Toast
	toastInfo.value.message = options.title
	toastInfo.value.type = options.icon === 'success' ? 'success' : 'error'
	toastInfo.value.show = true
	
	// 自动隐藏
	setTimeout(() => {
		toastInfo.value.show = false
	}, options.duration || 2000)
	// #endif
	
	// #ifndef H5
	// 非H5环境使用原生Toast
	uni.showToast(options)
	// #endif
}

const handleLogin = async () => {
	if (!canLogin.value || loading.value) {
		return
	}
	
	loading.value = true
	
	try {
		// 使用认证工具函数进行登录		
		const result = await loginApi(loginForm.value)
		
		// 登录成功
		showToast({
			title: '登录成功',
			icon: 'success',
			duration: 2000
		})
		
		// 保存登录数据
		saveLoginData(result.userInfo, result.token)
		
		// 处理记住密码
		if (loginForm.value.rememberMe) {
			saveCredentials(loginForm.value.account, loginForm.value.password)
		} else {
			clearSavedCredentials()
		}
		
		emit('login-success', {
			account: result.userInfo.account,
			name: result.userInfo.name,
			role: result.userInfo.role,
			token: result.token
		})
		
		emit('update:visible', false)
		
	} catch (error) {
		console.error('登录失败:', error)
		
		// 根据错误类型显示不同的错误信息
		let errorMessage = '登录失败，请重试'
		
		if (error.message) {
			// 如果后端返回了具体的错误信息，优先显示
			errorMessage = error.message
		} else if (error.code === 'NETWORK_ERROR') {
			errorMessage = '网络连接失败，请检查网络后重试'
		} else if (error.code === 'TIMEOUT') {
			errorMessage = '登录超时，请重试'
		}
		
		showToast({
			title: errorMessage,
			icon: 'error',
			duration: 3000
		})
	} finally {
		loading.value = false
	}
}

// 加载保存的登录信息
const loadSavedCredentials = () => {
	try {
		const { account, password } = getSavedCredentials()
		
		if (account && password) {
			loginForm.value.account = account
			loginForm.value.password = password
			loginForm.value.rememberMe = true
		}
	} catch (error) {
		console.error('加载保存的登录信息失败:', error)
	}
}

// 生命周期
onMounted(() => {
	loadSavedCredentials()
})

// 监听visible变化，自动聚焦
watch(() => props.visible, (newVal) => {
	if (newVal) {
		setTimeout(() => {
			focusUsername.value = true
		}, 300)
	}
})
</script>

<style scoped>
.login-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
	padding: 32rpx;
}

.modal-content {
	background: white;
	border-radius: 16rpx;
	width: 100%;
	max-width: 600rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	overflow: hidden;
}

.modal-header {
	padding: 32rpx 32rpx 16rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
}

.close-btn {
	font-size: 48rpx;
	color: #999;
	line-height: 1;
	padding: 8rpx;
	margin: -8rpx;
}

.modal-body {
	padding: 32rpx;
}

.form-item {
	margin-bottom: 32rpx;
}

.form-item:last-child {
	margin-bottom: 0;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 16rpx;
	font-weight: 500;
}

.form-input {
	width: 100%;
	height: 88rpx;
	padding: 0 24rpx;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333;
	background: #fafafa;
	box-sizing: border-box;
}

.form-input:focus {
	border-color: #2B5BA1;
	background: white;
}

.checkbox-item {
	margin-top: 24rpx;
}

.checkbox-label {
	display: flex;
	align-items: center;
}

.checkbox-text {
	font-size: 26rpx;
	color: #666;
	margin-left: 16rpx;
}

.modal-footer {
	padding: 16rpx 32rpx 32rpx;
}

.login-btn {
	width: 100%;
	height: 88rpx;
	background: #2B5BA1;
	color: white;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 500;
	display: flex;
	align-items: center;
	justify-content: center;
}

.login-btn[disabled] {
	background: #ccc;
	color: #999;
}

.login-btn:not([disabled]):active {
	background: #1e4080;
}

/* H5特定样式 */
/* #ifdef H5 */
.login-modal {
	backdrop-filter: blur(4px);
}

.modal-content {
	animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
	from {
		opacity: 0;
		transform: translateY(-50rpx) scale(0.9);
	}
	to {
		opacity: 1;
		transform: translateY(0) scale(1);
	}
}

/* 自定义Toast样式 */
.custom-toast {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 10000;
	padding: 24rpx 32rpx;
	border-radius: 12rpx;
	color: white;
	font-size: 28rpx;
	font-weight: 500;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
	animation: toastFadeIn 0.3s ease-out;
	max-width: 500rpx;
	text-align: center;
	word-wrap: break-word;
}

.custom-toast.success {
	background: #4caf50;
}

.custom-toast.error {
	background: #f44336;
}

.toast-text {
	color: white;
	font-size: 28rpx;
	line-height: 1.4;
}

@keyframes toastFadeIn {
	from {
		opacity: 0;
		transform: translate(-50%, -50%) scale(0.8);
	}
	to {
		opacity: 1;
		transform: translate(-50%, -50%) scale(1);
	}
}
/* #endif */
</style> 